import { _decorator, Component, instantiate, Label, Node, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

//IsoX 和 IsoY 为等轴网格坐标位于原点 (0, 0) 时的屏幕坐标
const IsoX: number = 0;
const IsoY: number = 0;
//IsoW 与 IsoH 则决定网格的大小及倾斜度（标准 2:1 比例分别使用 2 和 1）
const IsoW: number = 64;
const IsoH: number = 32;

@ccclass('GridMap')
export class GridMap extends Component {
    @property(Node)
    cell : Node;

    start() {
        for (let i = 0; i < 10; i++) {
            for (let j = 0; j < 8; j++) {
                let tile = instantiate(this.cell)
                tile.setParent(this.node)
                tile.setPosition(this.grid2Cocos(j, i))
                tile.getChildByName("Label").getComponent(Label).string = i + "," + j;
                console.log(i + "," + j)
                console.log(this.cocos2Grid(tile.position).x + "_" + this.cocos2Grid(tile.position).y)
            }
        }
    }

    update(deltaTime: number) {
        
    }

    grid2Cocos(x: number, y: number): Vec3 {
        let cx = IsoX + (x + y) * IsoW/2;
        let cy = IsoY + (x - y) * IsoH/2;
        return new Vec3(cx, cy, 0);
    }

    cocos2Grid(pos: Vec3): Vec2 {
        let gx = ((pos.x - IsoX) / IsoW - (pos.y - IsoY) / IsoH);
        let gy = ((pos.y - IsoY) / IsoH + (pos.x - IsoX) / IsoW);
        return new Vec2(gx, gy);
    }
}


